package com.building.service.impl;

import com.building.dao.DormitoryManagerDao;
import com.building.dao.LiverecordDao;
import com.building.dao.StudentDao;
import com.building.entity.DormitoryManager;
import com.building.entity.Scorerecord;
import com.building.dao.ScorerecordDao;
import com.building.entity.Student;
import com.building.response.ServerResponse;
import com.building.service.ScorerecordService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;

/**
 * (Scorerecord)表服务实现类
 *
 * @author TianCai
 * @since 2023-01-16 04:09:23
 */
@Service("scorerecordService")
public class ScorerecordServiceImpl implements ScorerecordService {
    @Resource
    private ScorerecordDao scorerecordDao;
    @Resource
    private StudentDao studentDao;
    @Resource
    private LiverecordDao liverecordDao;
    @Resource
    private DormitoryManagerDao dormitoryManagerDao;

    /**
     * 通过ID查询单条数据
     *
     * @param scoreId 主键
     * @return 实例对象
     */
    @Override
    public Scorerecord queryById(Integer scoreId) {
        return this.scorerecordDao.queryById(scoreId);
    }

    /**
     * 分页查询
     *
     * @param scorerecord 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<Scorerecord> queryByPage(Scorerecord scorerecord, PageRequest pageRequest) {
        long total = this.scorerecordDao.count(scorerecord);
        return new PageImpl<>(this.scorerecordDao.queryAllByLimit(scorerecord, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param scorerecord 实例对象
     * @return 实例对象
     */
    @Override
    public Scorerecord insert(Scorerecord scorerecord) {
        this.scorerecordDao.insert(scorerecord);
        return scorerecord;
    }

    /**
     * 修改数据
     *
     * @param scorerecord 实例对象
     * @return 实例对象
     */
    @Override
    public Scorerecord update(Scorerecord scorerecord) {
        this.scorerecordDao.update(scorerecord);
        return this.queryById(scorerecord.getScoreId());
    }

    /**
     * 通过主键删除数据
     *
     * @param scoreId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer scoreId) {
        return this.scorerecordDao.deleteById(scoreId) > 0;
    }

    @Override
    public ServerResponse<Scorerecord> ScoreAdd(Integer sid, Integer  mid,Integer score) {
        Scorerecord scorerecord1 = this.scorerecordDao.queryByMidAndMid(sid, mid);
        if (scorerecord1!=null) return ServerResponse.createByErrorMessage("您已经给此位老师打过分啦!");
        Student student = this.studentDao.queryById(sid);
        if (student==null) return ServerResponse.createByErrorMessage("此学生信息有误不可打分!");
        Scorerecord scorerecord = new Scorerecord();
        scorerecord.setNumber(score);
        scorerecord.setSId(sid);
        scorerecord.setCreatetime(new Date());
        scorerecord.setDMId(mid);
        int insert = scorerecordDao.insert(scorerecord);
        DormitoryManager dormitoryManager = this.dormitoryManagerDao.queryById(mid);
        //  打分条数大于等于三条时 计分规则去掉一个最高分,去掉一个最低分,算平均分,
        //  如果小于3条的时候直接算平均分
        List<Scorerecord> scorerecords = this.scorerecordDao.queryByMid(mid);//拿到这个宿管的所有打分记录
        if (scorerecords.size()>=3){
            Optional<Scorerecord> max = scorerecords.stream().collect(Collectors.maxBy(comparing(Scorerecord::getNumber)));
            Optional<Scorerecord> min = scorerecords.stream().collect(Collectors.minBy(comparing(Scorerecord::getNumber)));
            scorerecords.remove(max.get());//去掉一个最高分
            scorerecords.remove(min.get());//去掉一个最低分
            int count = 0;
            for (int i = 0;i< scorerecords.size();i++){
                count+=scorerecords.get(i).getNumber();
            }
            int avg = count / scorerecords.size();
            dormitoryManager.setScore(avg);
            dormitoryManager.setVersion(dormitoryManager.getVersion()+1);
            dormitoryManager.setUpdateTime(new Date());
            int update = dormitoryManagerDao.update(dormitoryManager);
            if (update!=1) return ServerResponse.createByErrorMessage("修改失败请检查服务器!");
            return ServerResponse.createBySuccess("打分成功!",scorerecord);
        }else{//小于三条
            //求和
            Integer sum= scorerecords.stream().collect(Collectors.summingInt(Scorerecord::getNumber));
            dormitoryManager.setScore(sum/scorerecords.size());//求平均值
            dormitoryManager.setVersion(dormitoryManager.getVersion()+1);
            dormitoryManager.setUpdateTime(new Date());
            int update = dormitoryManagerDao.update(dormitoryManager);
            if (update!=1) return ServerResponse.createByErrorMessage("修改失败请检查服务器!");
            return ServerResponse.createBySuccess("打分成功!",scorerecord);
        }
    }
}
